package model

import (
	"gorm.io/gorm"
	"member_srv/basic/config"
	"time"
)

type Video struct {
	Id        uint32         `gorm:"column:id;type:int UNSIGNED;primaryKey;not null;" json:"id"`
	Title     string         `gorm:"column:title;type:varchar(60);not null;" json:"title"`
	Info      string         `gorm:"column:info;type:varchar(90);not null;" json:"info"`
	Tag       string         `gorm:"column:tag;type:varchar(60);not null;" json:"tag"`
	Level     int8           `gorm:"column:level;type:tinyint(1);not null;" json:"level"`
	Image     string         `gorm:"column:image;type:varchar(300);not null;" json:"image"`
	Status    int8           `gorm:"column:status;type:tinyint(1);not null;" json:"status"`
	CreatedAt time.Time      `gorm:"column:created_at;type:datetime(3);not null;default:CURRENT_TIMESTAMP(3);" json:"created_at"`
	UpdatedAt time.Time      `gorm:"column:updated_at;type:datetime(3);not null;default:CURRENT_TIMESTAMP(3);" json:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:datetime(3);default:NULL;" json:"deleted_at"`
}

func (v *Video) TableName() string {
	return "video"
}

func (v *Video) AddVideo() error {
	return config.DB.Create(&v).Error
}

func (v *Video) TagVideo(tga string) (list []*Video, err error) {
	err = config.DB.Where("tag = ?", tga).Find(&list).Error
	return
}

func (v *Video) KeyVideo(key string) (list []*Video, err error) {
	err = config.DB.Where("tag = ? or info = ? or title = ?", key, key, key).Find(&list).Error
	return
}

func (v *Video) ListVideo() (list []*Video, err error) {
	err = config.DB.Find(&list).Error
	return
}

func (v *Video) ListOrderVideo() (list []*Video, err error) {
	err = config.DB.Order("tag desc").Find(&list).Error
	return
}

func (v *Video) ListPageVideo(page, pageSize int) (list []*Video, err error) {
	err = config.DB.Scopes(Paginate(page, pageSize)).Find(&list).Error
	return
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
